package cn.itcast.service.system.impl;

import cn.itcast.dao.system.ModuleDao;
import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
public class ModuleServiceImpl implements ModuleService {
    @Autowired
    private ModuleDao moduleDao;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public PageInfo<Module> findByPage(int pageNum, int pageSize, String companyId) {
        //设置开始页面与页面大小
        PageHelper.startPage(pageNum, pageSize);
        List<Module> list = moduleDao.findAll();
        //构造一个pageinfo对象
        PageInfo<Module> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<Module> findAll() {
        return moduleDao.findAll();
    }

    @Override
    public void save(Module module) {
        //设置主键
        module.setId(UUID.randomUUID().toString());
        moduleDao.save(module);
    }

    @Override
    public void update(Module module) {
        moduleDao.update(module);
    }
    //根据id查找模块
    @Override
    public Module findById(String id) {
        return moduleDao.findById(id);
    }
    //根据模块id删除模块
    @Override
    public void delete(String id) {
        //查询该模块是否有子模块
        moduleDao.delete(id);

    }

    @Override
    public List<String> findRoleModuleByRoleId(String roleid) {
        ValueOperations value = redisTemplate.opsForValue();
        List<String> list = (List<String>) value.get(roleid);
        if (list!=null&&list.size()!=0){
            return list;
        }else {
            list=moduleDao.findModulsIdsByRoleId(roleid);
            value.set(roleid,list);
            return list;
        }

    }

    @Override
    public List<Module> findModuleByUser(User user) {
        //获取用户的等级
        Integer degree = user.getDegree();
        List<Module>resultList=null;
        //判断用户的等级
        if (degree==0||degree==1){
            //根据用户等级查看
            resultList=moduleDao.findModuleByDegree(degree);
        }else {
            //普通用户是需要根据用户的角色查看
            resultList=moduleDao.findModuleByUserId(user.getId());
        }
        return resultList;

    }
}
